<template>
  <j-modal
    title="批量添加采购价格方案"
    :width="1200"
    :visible="visible"
    :footer="null"
    switchFullscreen
    @cancel="visible = false"
  >
    <!--    搜索栏-->
    <div>
      <div class="search-area">
        <div style="display: flex">
          <a-space @keyup.enter="handleSearch">
            物料名称：
            <a-input v-model="queryParam.materialName" style="width: 240px" placeholder="请输入物料名称"></a-input>
            物料类型：
            <j-dict-select-tag
              dict-code="hf_material_type,material_type_name,id"
              v-model="queryParam.materialType"
              style="width: 160px"
              placeholder="请选择物料类型"
            ></j-dict-select-tag>
          </a-space>
        </div>
        <div>
          <!--    操作栏-->
          <a-space>
            <a-button type="primary" icon="search" @click="handleSearch">查询</a-button>
            <a-button type="primary" icon="reload" @click="handleReset">重置</a-button>
            <a-button v-if="!editable" type="primary" icon="edit" @click="edit">编辑</a-button>
            <a-button v-else type="primary" icon="save" @click="save">保存</a-button>
            <a-button type="primary" icon="plus" @click="openBatchAddPurchasePriceList">查询已添加的数据</a-button>
          </a-space>
        </div>
      </div>
      <a-space>
        批量录入==>单价：
        <a-input-number
          :style="{ width: inputNumberWidth }"
          placeholder=""
          @keyup.enter.stop="handlePriceChange"
        ></a-input-number>
        税率：
        <a-input-number
          :style="{ width: inputNumberWidth }"
          placeholder=""
          @keyup.enter.stop="handleTaxChange"
        ></a-input-number>
        含税单价：
        <a-input-number
          :style="{ width: inputNumberWidth }"
          placeholder=""
          @keyup.enter.stop="handleTaxPriceChange"
        ></a-input-number>
        供应商：
        <j-search-select-tag
          dict="hf_supplier,name,id"
          style="width: 200px"
          placeholder=""
          @change="handleSupplierChange"
        ></j-search-select-tag>
        执行时间：
        <j-date style="width: 100px" @change="handleUseTimeChange"></j-date>
      </a-space>
    </div>

    <!--    内容栏-->
    <div>
      <a-button type="primary" icon="plus" style="margin-bottom: 8px" @click="addToBatchAddList">添加</a-button>
      <a-table
        ref="table"
        size="middle"
        :scroll="{ x: true }"
        bordered
        rowKey="id"
        :columns="columns"
        :dataSource="dataSource"
        :pagination="ipagination"
        :loading="loading"
        :rowSelection="{ selectedRowKeys: selectedRowKeys, onChange: onSelectChange }"
        class="j-table-force-nowrap"
        @change="handleTableChange"
      >
        <template
          v-for="slotName in ['purchaseCode', 'purchaseCode1', 'qad']"
          :slot="slotName"
          slot-scope="text, record"
        >
          <a-input
            v-if="editable && selectedRowKeys.includes(record.id)"
            style="width: 100%"
            placeholder="请输入"
          ></a-input>
          <span v-else slot-scope="text, record">
            {{ text }}
          </span>
        </template>
        <template slot="price" slot-scope="text, record">
          <a-input
            v-if="editable && selectedRowKeys.includes(record.id)"
            :style="{ width: inputNumberWidth }"
            v-model="record['price']"
          ></a-input>
          <span v-else slot-scope="text, record">
            {{ text }}
          </span>
        </template>
        <template slot="tax" slot-scope="text, record">
          <a-input-number
            v-if="editable && selectedRowKeys.includes(record.id)"
            :style="{ width: inputNumberWidth }"
            v-model="record['tax']"
            :formatter="value => `${value}%`"
          ></a-input-number>
          <span v-else slot-scope="text, record">
            {{ text }}
          </span>
        </template>
        <template slot="taxPrice" slot-scope="text, record">
          <a-input-number
            v-if="editable && selectedRowKeys.includes(record.id)"
            v-model="record['taxPrice']"
            :style="{ width: inputNumberWidth }"
          ></a-input-number>
          <span v-else slot-scope="text, record">
            {{ text }}
          </span>
        </template>
        <template slot="useTime" slot-scope="text, record">
          <j-search-select-tag
            dict="hf_supplier,name,id"
            v-if="editable && selectedRowKeys.includes(record.id)"
            v-model="record['useTime']"
            style="width: 100%"
          ></j-search-select-tag>
          <span v-else slot-scope="text, record">
            {{ record['useTime'] }}
          </span>
        </template>
        <template slot="supplierId" slot-scope="text, record">
          <j-search-select-tag
            dict="hf_supplier,name,id"
            v-if="editable && selectedRowKeys.includes(record.id)"
            v-model="record['customId']"
            style="width: 100%"
          ></j-search-select-tag>
          <span v-else slot-scope="text, record">
            {{ record['supplierId_dictText'] }}
          </span>
        </template>
        <template slot="remark" slot-scope="text, record">
          <a-textarea
            v-if="editable && selectedRowKeys.includes(record.id)"
            v-model="record['remark']"
            style="width: 100%"
          ></a-textarea>
          <span v-else slot-scope="text, record">
            {{ record['remark'] }}
          </span>
        </template>
      </a-table>
    </div>

    <HfBatchAddPurchasePriceList
      :table-data="addedDataSource"
      @delete="handleDeleteAddedData"
      ref="hfBatchAddPurchasePriceListRef"
      @ok="handleOk"
      @fillFields="handleFillFields"
    />
  </j-modal>
</template>

<script>
import '@/assets/less/TableExpand.less'
import { JeecgListMixin } from '@/mixins/JeecgListMixin'
import HfBatchAddPurchasePriceList from '@views/purchase/modules/HfBatchAddPurchasePriceList.vue'
import { Modal } from 'ant-design-vue'
import { getAction } from '@api/manage'

export default {
  name: 'HfBatchAddPurchasePrice',
  components: { HfBatchAddPurchasePriceList },
  mixins: [JeecgListMixin],
  watch: {
    dataSource: {
      handler(newData, oldData) {
        if (this.editStatus) {
          const newIds = newData.filter(item => this.addedDataSource.some(addedItem => addedItem.id === item.id))
          this.selectedRowKeys = newIds.map(item => item.id)
          this.editStatus = false
        }
      }
    }
  },
  data() {
    return {
      visible: false,
      inputNumberWidth: '80px',
      editable: false,
      queryParams: {
        materialName: ''
      },
      disableMixinCreated: true,
      columns: [
        {
          title: '序号',
          fixed: 'left',
          width: 60,
          align: 'center',
          customRender: (t, r, index) => {
            return index + 1
          }
        },
        {
          title: '物料代码',
          dataIndex: 'materialCode',
          align: 'center',
          width: 120,
          fixed: 'left'
        },
        {
          title: '物料名称',
          dataIndex: 'materialName',
          align: 'center',
          width: 180,
          fixed: 'left'
        },
        {
          title: '规格型号',
          dataIndex: 'sap',
          align: 'center'
        },
        {
          title: '单价',
          dataIndex: 'price',
          align: 'center',
          scopedSlots: { customRender: 'price' }
        },
        {
          title: '税率',
          dataIndex: 'tax',
          align: 'center',
          scopedSlots: { customRender: 'tax' }
        },
        {
          title: '含税单价',
          dataIndex: 'taxPrice',
          align: 'center',
          scopedSlots: { customRender: 'taxPrice' }
        },
        {
          title: '执行时间',
          dataIndex: 'useTime',
          align: 'center',
          scopedSlots: { customRender: 'useTime' }
        },
        {
          title: '供应商',
          dataIndex: 'supplierId',
          align: 'center',
          scopedSlots: { customRender: 'supplierId' }
        },
        {
          title: '供应商品番',
          dataIndex: 'supplierCode',
          align: 'center',
          scopedSlots: { customRender: 'supplierCode' }
        },
        {
          title: '供应商简号',
          dataIndex: 'supplierCode1',
          align: 'center',
          scopedSlots: { customRender: 'supplierCode1' }
        },
        {
          title: 'QAD',
          dataIndex: 'qad',
          align: 'center',
          scopedSlots: { customRender: 'qad' }
        },
        {
          title: '备注',
          dataIndex: 'remark',
          align: 'center',
          scopedSlots: { customRender: 'remark' }
        }
      ],
      ipagination: {
        current: 1,
        pageSize: 10,
        pageSizeOptions: ['10', '15', '20', '25', '30'],
        showTotal: (total, range) => {
          return range[0] + '-' + range[1] + ' 共' + total + '条'
        },
        showQuickJumper: true,
        showSizeChanger: true,
        total: 0
      },
      url: {
        list: '/material/hfMaterial/list'
      },
      addedDataSource: [],
      editStatus: false
    }
  },
  computed: {},
  methods: {
    handleSearch() {
      this.loadData()
      this.dataSource.forEach(item => {
        item.price = ''
        item.tax = ''
        item.taxPrice = ''
      })
    },
    handleReset() {
      this.dataSource = this.dataSource.map(item => {
        item.price = ''
        item.tax = ''
        item.taxPrice = ''
        return item
      })
    },
    handlePriceChange(e) {
      const price = e.target.value
      const newData = [...this.dataSource]
      const selectedRows = newData.filter(row => this.selectedRowKeys.includes(row.id))
      if (selectedRows.length === 0) {
        this.$message.error('请选择要添加的数据')
        return
      }
      selectedRows.forEach(item => {
        const index = newData.findIndex(row => row.id === item.id)
        if (index !== -1) {
          newData[index].price = price
          if (newData[index].tax) {
            newData[index].taxPrice = (price * (1 + newData[index].tax / 100)).toFixed(4)
            return
          }
          if (newData[index].taxPrice && !newData[index].tax) {
            newData[index].tax = (newData[index].taxPrice / price) * 100
          }
        }
      })
      this.dataSource = newData
    },
    handleTaxChange(e) {
      const tax = e.target.value
      const newData = [...this.dataSource]
      const selectedRows = newData.filter(row => this.selectedRowKeys.includes(row.id))
      if (selectedRows.length === 0) {
        this.$message.error('请选择要添加的数据')
        return
      }
      selectedRows.forEach(item => {
        const index = newData.findIndex(row => row.id === item.id)
        if (index !== -1) {
          newData[index].tax = tax
          if (newData[index].price) {
            newData[index].taxPrice = (newData[index].price * (1 + newData[index].tax / 100)).toFixed(4)
            return
          }
          if (newData[index].taxPrice && !newData[index].price) {
            newData[index].price = (newData[index].taxPrice / tax) * 100
          }
        }
      })
      this.dataSource = newData
    },
    handleTaxPriceChange(e) {
      const taxPrice = e.target.value
      const newData = [...this.dataSource]
      const selectedRows = newData.filter(row => this.selectedRowKeys.includes(row.id))
      if (selectedRows.length === 0) {
        this.$message.error('请选择要添加的数据')
        return
      }
      selectedRows.forEach(item => {
        const index = newData.findIndex(row => row.id === item.id)
        if (index !== -1) {
          newData[index].taxPrice = taxPrice.toFixed(4)
          if (newData[index].price && !newData[index].tax) {
            newData[index].tax = (newData[index].taxPrice / newData[index].price) * 100
            return
          }
          if (newData[index].tax && !newData[index].price) {
            newData[index].price = (newData[index].taxPrice / newData[index].tax) * 100
          }
        }
      })
      this.dataSource = newData
    },
    handleSupplierChange(value, text) {
      const newData = [...this.dataSource]
      const selectedRows = newData.filter(row => this.selectedRowKeys.includes(row.id))
      if (selectedRows.length === 0) {
        this.$message.error('请选择要添加的数据')
        return
      }
      selectedRows.forEach(item => {
        const index = newData.findIndex(row => row.id === item.id)
        if (index !== -1) {
          newData[index].supplierId = value
          newData[index].supplierId_dictText = text
        }
      })
      this.dataSource = newData
    },
    handleUseTimeChange(value) {
      const newData = [...this.dataSource]
      const selectedRows = newData.filter(row => this.selectedRowKeys.includes(row.id))
      if (selectedRows.length === 0) {
        this.$message.error('请选择要添加的数据')
        return
      }
      selectedRows.forEach(item => {
        const index = newData.findIndex(row => row.id === item.id)
        if (index !== -1) {
          newData[index].useTime = value
        }
      })
      this.dataSource = newData
    },
    edit() {
      this.editable = true
    },
    save() {
      this.editable = false
    },
    addToBatchAddList() {
      // 有没有选中
      if (this.selectionRows.length === 0) {
        this.$message.error('请选择要添加的数据')
        return
      }
      // 单价、税率、含税单价是否都有值
      const selectedRows = this.selectionRows.filter(row => row.price && row.tax && row.taxPrice)
      if (selectedRows.length === 0) {
        this.$message.error('请完善单价、税率、含税单价')
        return
      }
      // 筛选重复项
      const repeatRows = this.addedDataSource.filter(selectedItem => this.selectedRowKeys.includes(selectedItem.id))
      const uniqueRows = this.addedDataSource.filter(selectedItem => !this.selectedRowKeys.includes(selectedItem.id))
      if (repeatRows.length > 0) {
        Modal.confirm({
          title: '提示',
          content: h =>
            h('div', [
              h('div', '以下数据已存在,是否覆盖？'),
              h(
                'ul',
                { style: { marginTop: '8px', paddingLeft: '16px' } },
                repeatRows.map(item => h('li', { key: item.id }, item.materialName + '--' + item.price))
              )
            ]),
          width: 700,
          okText: '覆盖',
          cancelText: '只添加不重复的',
          maskClosable: true,
          onOk: () => {
            this.addedDataSource.push(...uniqueRows)
            repeatRows.forEach(repeatItem => {
              const index = this.addedDataSource.findIndex(addedItem => addedItem.id === repeatItem.id)
              if (index !== -1) {
                this.addedDataSource[index] = repeatItem
              }
            })
            this.$message.success('添加成功')
          },
          onCancel: () => {
            this.addedDataSource.push(...uniqueRows)
            if (uniqueRows.length > 0) {
              this.$message.success('添加成功')
            }
          }
        })
      } else {
        this.addedDataSource.push(...this.selectionRows)
        this.$message.success('添加成功')
      }
    },
    openBatchAddPurchasePriceList() {
      this.$refs.hfBatchAddPurchasePriceListRef.visible = true
    },
    loadData(arg) {
      if (!this.url.list) {
        this.$message.error('请设置url.list属性!')
        return
      }
      //加载数据 若传入参数1则加载第一页的内容
      if (arg === 1) {
        this.ipagination.current = 1
      }
      let params = this.getQueryParams() //查询条件
      this.loading = true
      getAction(this.url.list, params)
        .then(res => {
          if (res.success) {
            this.dataSource = res.result.records || res.result
            this.dataSource.forEach(item => {
              item.materialId = item.id
            })
            this.editStatus = true
            this.ipagination.total = res.result.total
          } else {
            this.$message.warning(res.message)
          }
        })
        .finally(() => {
          this.loading = false
        })
    },
    handleDeleteAddedData(selectedRowKeys) {
      this.addedDataSource = this.addedDataSource.filter(item => !selectedRowKeys.includes(item.id))
    },
    close() {
      this.visible = false
      this.dataSource = []
      this.addedDataSource = []
      this.$emit('close')
    },
    handleOk() {
      this.close()
      this.$emit('ok')
    },
    handleFillFields() {
      const newData = [...this.addedDataSource]
      newData.map(item => {
        item.purchaseCode = item.sap
        return {
          ...item
        }
      })
      this.addedDataSource = newData
    }
  }
}
</script>
<style scoped>
@import '~@assets/less/common.less';

.search-area {
  display: flex;
  justify-content: space-between;
  margin-bottom: 10px;
}
</style>
